package vip.meeet.algorithm.link;

import java.math.BigInteger;

/**
 * 2
 */
public class TwoNumAdd {

    public static void main(String[] args) {

        ListNode listNode = build("342");
        print(listNode);
    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        BigInteger numA = getNum(l1);
        BigInteger numB = getNum(l2);
        BigInteger rs = numA.add(numB);
        String string = rs.toString();
        return build(string);
    }

    public static ListNode build(String num){
        ListNode first = new ListNode(Integer.parseInt(String.valueOf(num.charAt(num.length()-1))));
        ListNode tmp = first;
        for(int i=num.length()-2;i>=0;i--){
            ListNode cur = new ListNode(Integer.parseInt(String.valueOf(num.charAt(i))));
            tmp.next = cur;
            tmp = cur;
        }
        return first;
    }

    public static BigInteger getNum(ListNode node){
        StringBuilder sb = new StringBuilder();
        do{
            sb.append(String.valueOf(node.val));
            node = node.next;
        }while (node != null);
        return new BigInteger(sb.reverse().toString());
    }

    public static void print(ListNode node){
        StringBuilder sb = new StringBuilder();
        do{
            sb.append(node.val).append(" -> ");
            node = node.next;
        }while (node != null);
        System.out.println(sb.subSequence(0,sb.length() - 4));
    }

    public static class ListNode {
      int val;
      ListNode next;
      ListNode(int x) { val = x; }
   }

}
